class Solution {
    public static int minOperations1(int[] nums, int x) {
        int sum = 0;
        for (int a : nums) {
            sum += a;
        }
        int target = sum - x;
        if (target < 0) {
            return -1;
        }
        int len = -1;
        sum = 0;
        for (int right = 0, left = 0; right <nums.length; right++) {
            sum += nums[right];
            while(sum > target) {
                sum -= nums[left++];//出窗口
            }
            if (sum == target) {
                len = Math.max(len, right-left+1); // 记录此时的长度
            }
        }
        return len == 0 ? -1 : nums.length-len;
    }

    public static int minOperations(int[] nums, int x) {
        int sum = 0;
        for(int a : nums) sum += a;
        int target = sum -x;
        if (target < 0)  return -1;
        int ret = -1;
        for(int left = 0, right = 0, tmp = 0; right < nums.length; right++) {
            tmp += nums[right];
            while (tmp > target) {
                tmp -= nums[left];
                left++;
            }
            if (tmp == target) {
                ret = Math.max(ret, right-left+1);
            }
        }
        if (ret == -1) {
            return ret;
        } else {
            return nums.length-ret;
        }
    }

    public static void main(String[] args) {
        int[] nums = {8828,9581,49,9818,9974,9869,9991,10000,10000,10000,9999,9993,9904,8819,1231,6309};
        System.out.println(minOperations(nums, 134365));
    }
}